package me.duzhi.ilog.cms.plugins.changyan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.jpress.Consts;
import io.jpress.core.BaseFrontController;
import io.jpress.front.controller.UserController;
import io.jpress.message.Actions;
import io.jpress.message.MessageKit;
import io.jpress.model.query.OptionQuery;
import io.jpress.model.query.UserQuery;
import io.jpress.router.RouterMapping;
import io.jpress.utils.CookieUtils;
import io.jpress.utils.EncryptUtils;
import io.jpress.utils.StringUtils;
import org.codehaus.plexus.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

@RouterMapping(url = "/changyan")
public class ChangyanController extends BaseFrontController {

    public void loginByChangYanAuth() {
        String redirect = OptionQuery.me().findValue("web_domain");
        String client_id = OptionQuery.me().findValue("cms.pintu_changyan_APP_ID");
        String pl = getPara("auth");
        StringBuffer sb = new StringBuffer();
        sb.append("https://changyan.sohu.com/api/oauth2/authorize?client_id=");
        sb.append(client_id);
        sb.append("&redirect_uri="+redirect+"/changyan/redirect");
        sb.append("&response_type=code&platform_id=" + pl);
        redirect(sb.toString());
    }

    public void redirect() {
        String CODE = getPara("CODE");
        setSessionAttr("CHANGYAN_AUTH_CODE", CODE);
        String _goto = CookieUtils.get(this, "redirecturl_Referer");
        if(StringUtils.isBlank(_goto)){
            _goto = "/?redirect=true&_goto=false";
        }
        setAttr("goto",_goto);
        render("redirect.html");
    }

    public void getUserInfo() throws IOException {
        String callback = getPara("callback");
        UserInfo userinfo = new UserInfo();
        io.jpress.model.User loginedUser = getLoginedUser();
        if (loginedUser == null) {//此处为模拟逻辑，具体实现可以变化
            userinfo.setIs_login(0);//用户未登录
        } else {
            userinfo.setIs_login(1);//用户已登录
            User user = new User();
            user.setUser_id(loginedUser.getId().intValue()); //该值具体根据自己用户系统设定
            user.setNickname(loginedUser.getNickname()); //该值具体根据自己用户系统设定
            user.setImg_url(loginedUser.getAvatar()); //该值具体根据自己用户系统设定，可以为空
            user.setProfile_url("/user/center");//该值具体根据自己用户系统设定，可以为空
            user.setSign(loginedUser.getSignature()); //签名已弃用，任意赋值即可
            userinfo.setUser(user);
        }
        renderJavascript(callback + "(" + JSONArray.toJSONString(userinfo) + ")");
    }

    public void checkuserlogined() {
        if (getLoginedUser() != null) {
            renderAjaxResultForSuccess();
            return;
        }
        String changyanKey = "CMSCHANGYAN_";
        String userInformation = getPara("information");
        JSONObject object = (JSONObject) JSON.parse(userInformation);
        if (object == null) {
            renderAjaxResultForError();
            return;
        }
        String sign = object.getString("sign");
        String error_code = object.getString("error_code");
        if (!"0".equals(error_code)) {
        }
        String user_id = object.getString("user_id");
        if (checkIsNull(sign)) return;
        if (checkIsNull(user_id)) return;
        io.jpress.model.User checkUser = UserQuery.me().findUserByUsername(changyanKey + user_id);
        if (checkUser != null) {
            /**
             * 登录用户
             */
            MessageKit.sendMessage(Actions.USER_LOGINED, checkUser);
            CookieUtils.put(this, Consts.COOKIE_LOGINED_USER, checkUser.getId());
        }
        io.jpress.model.User user = new io.jpress.model.User();
        if (checkIsNull(userInformation)) return;

        String avatar = object.getString("img_url");
        if (checkIsNull(avatar)) return;
        String nickname = object.getString("nickname");
        if (checkIsNull(nickname)) return;
        String source = object.getString("from");
        String profile_url = object.getString("profile_url");
        if (checkIsNull(sign)) return;
        user.setAvatar(avatar);
        user.setNickname(nickname);
        String salt = EncryptUtils.salt();
        user.setSalt(salt);
        user.setPassword(EncryptUtils.encryptPassword("password1111111111111111", salt));
        user.setCreateSource("畅言:" + source);
        user.setUsername("CMSCHANGYAN_" + user_id);
        String appkey = OptionQuery.me().findValue("cms.pintu_changyan_APP_KEY");
     /*   if (CheckSign.sign(appkey, avatar, nickname, profile_url, user_id).equals(sign
        )) {*/
        user.save();
        user.createMetadata("changyan_userinfo",object.toJSONString()).saveOrUpdate();
        /**
         * 登录用户
         */
        MessageKit.sendMessage(Actions.USER_LOGINED, user);
        CookieUtils.put(this, Consts.COOKIE_LOGINED_USER, user.getId());
       /* }*/
        renderAjaxResultForSuccess();

    }


    private boolean checkIsNull(String avatar) {
        if (StringUtils.isBlank(avatar)) {
            renderAjaxResultForError("非法提交");
            return true;
        }
        return false;
    }
}

